package com.luo.util;

import com.alibaba.fastjson.JSON;
import com.luo.model.ResultObj;
import redis.clients.jedis.Jedis;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 功能：
 * 作者：Luo。
 * 日期：2024/2/14 10:28
 */
public class TokenId {
    public static Object getUserId(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String authorization = req.getHeader("authorization");
        String index = "Bearer ";
        if (authorization != null) {
            authorization = authorization.substring(authorization.lastIndexOf(index) + index.length());
            // 拿到token进行判断该token是否过期
            // 连接到Redis
            Jedis jedis = RedisUtil.getJedis();
            String fieldValue = jedis.hget(authorization, "token");
            String username = jedis.hget(authorization, "currentTime");
            String id = jedis.hget(authorization, "id");
            if (id == null) {
                // 说明token过期了
                ResultObj resultObj = new ResultObj();
                resultObj.setCode("-3");
                resultObj.setMsg("token已过期");
                String jsonString = JSON.toJSONString(resultObj);
                resp.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                resp.getWriter().write(jsonString);
                resp.getWriter().close();
                return null;
            }
            return id;
        } else {
            return null;
        }
    }
}
